package com.fqgj.sentry.aop;

import com.fqgj.sentry.common.cache.RequestLocalInfo;
import com.fqgj.sentry.manage.entity.McLogEntity;
import com.fqgj.sentry.manage.entity.McUserEntity;
import com.fqgj.sentry.manage.service.LogService;
import com.fqgj.sentry.manage.service.UserService;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by ykpbean kangping.ying@yuntu-inc.com
 *
 * @description
 * @create 2017-07-19 下午8:16
 */

@Aspect
@Component
public class ArchivesLogAop {

    private String requestUri = null; // 请求地址
    private String userId = ""; // 用户名
    private String operateSys = ""; //操作系统
    private String browser = ""; //浏览器
    private String ip = "";//操作ip
    private Date gtmCreate = null; // 创建时间
    private HttpServletRequest request = null;


    @Autowired
    private LogService logService;
    @Autowired
    private UserService userService;

    //controller层切入点
    @Pointcut("@annotation(com.fqgj.sentry.aop.ArchivesLog)")
    public void controllerAspect() {
        System.out.println("========controllerAspect===========");
    }

    /**
     * 日志收集
     * @param joinPoint
     */
    @After("controllerAspect()")
    public void doAfter(JoinPoint joinPoint) {
        this.request = getHttpServletRequest();
        String agent=request.getHeader("User-Agent");
        UserAgent userAgent=UserAgent.parseUserAgentString(agent);
        operateSys=userAgent.getOperatingSystem().getName();
        browser=userAgent.getBrowser().getName();
        this.requestUri = request.getRequestURI();
        this.ip = request.getRemoteAddr();
        McUserEntity userEntity=userService.selectById(RequestLocalInfo.getCurrentUserId());
        McLogEntity logEntity=new McLogEntity()
                .setUri(requestUri)
                .setIp(ip)
                .setBrowser(browser)
                .setOperateSys(operateSys)
                .setUserId(userEntity.getId())
                .setEmail(userEntity.getAccount());
        logService.insertLog(logEntity);

    }

    /**
     * 获取 HttpServletRequest
     *
     * @return
     */
    public HttpServletRequest getHttpServletRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }

}
